package com.modifiertech.lineage.client.gui;

import com.feed_the_beast.ftblib.lib.icon.Color4I;
import com.modifiertech.lineage.BaseConst;
import com.modifiertech.lineage.api.LineageModAccess;
import com.modifiertech.lineage.api.PlayerData;
import com.modifiertech.lineage.api.PlayerDataShortCutTag;
import com.modifiertech.lineage.base.ConfigHandler;
import com.modifiertech.lineage.client.gui.ftbint.GuiIconsV2;
import com.modifiertech.lineage.event.PlayerDataHandler;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.IAttributeInstance;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.MobEffects;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.MathHelper;
import net.minecraftforge.client.GuiIngameForge;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

import java.util.Optional;

/**血条界面UI渲染
 *
 */
public class LevelAndExpRender extends Gui {
    public static final LevelAndExpRender INSTANCE=new LevelAndExpRender();
    private LevelAndExpRender(){}

    private static final ResourceLocation TEXTURE=new ResourceLocation(BaseConst.MODID,"textures/gui/hud2.png");

    @SubscribeEvent(receiveCanceled = true)
    //该SideOnly 内部方法依赖上层Gui 方法,无法迁出Proxy,为必要注解
    @SideOnly(value = Side.CLIENT)
    public void onLevelEntityRender(RenderGameOverlayEvent.Pre event){
        Minecraft mc = Minecraft.getMinecraft();
        EntityPlayer player = mc.player;
        if(event.getType() == RenderGameOverlayEvent.ElementType.HEALTH ){
            event.setCanceled(true);
            renderHearts(event,mc,player);
        }
    }

    /**渲染血条、魔法条、技能快捷图标以及技能cd
     *
     * @param event
     * @param mc
     * @param player
     */
    private void renderHearts(RenderGameOverlayEvent event, Minecraft mc, EntityPlayer player) {

        int width = event.getResolution().getScaledWidth();
        int height = event.getResolution().getScaledHeight();
        final int left = width / 2 - 92;
        final int top = height - GuiIngameForge.left_height;


        GlStateManager.enableBlend();
        mc.renderEngine.bindTexture(TEXTURE);
        //血条底栏
        drawTexturedModalRect(left+ ConfigHandler.leftmodify, top+ConfigHandler.topmodify,
                0+ConfigHandler.textureleftmodify, 0+ConfigHandler.texturetopmodify
                , 128+ConfigHandler.weightmodify, 32+ConfigHandler.heightmodify);
        //血球底色
        drawTexturedModalRect(left+ ConfigHandler.leftmodify_orb, top+ConfigHandler.topmodify_orb,
                128, 0
                , 56, 56);
        //魔法球底色
        drawTexturedModalRect(left+ ConfigHandler.leftmodify_mana_orb, top+ConfigHandler.topmodify_mana_orb,
                128, 0
                , 56, 56);

        //54-106
        int health = MathHelper.ceil(player.getHealth());
        IAttributeInstance attrMaxHealth = player.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH);
        int healthMax = MathHelper.ceil(attrMaxHealth.getAttributeValue());
        // 19/20 54
        float hpper=(float)health/healthMax;
        //损失的血量
        int loseHealthLenghth=52-(MathHelper.ceil(52*hpper));
        //当前的血量
        int current=106-(MathHelper.ceil(52*hpper));
        //渲染的血球长度
        int heightOrbHealth=52- MathHelper.ceil  (52*(1-hpper));

        double mana = Math.round(PlayerDataHandler.get(mc.player).getCurrentMana() * 10.0) / 10.0;
        double manaMax = PlayerDataHandler.get(mc.player).getMaxMana();
        double manaper= mana/manaMax;

        //损失的魔法转换长度
        int loseManaLenghth=52-(MathHelper.ceil(52*manaper));
        //当前的魔法量转换长度
        int currentManaLength=161-(MathHelper.ceil(52*manaper));
        //渲染的魔法球长度
        int heightOrbMana=52- MathHelper.ceil  (52*(1-manaper));


        //health orb
        drawTexturedModalRect(left+ ConfigHandler.leftmodify_orb, top+ConfigHandler.topmodify_orb+loseHealthLenghth,
                128, current
                , 56, heightOrbHealth);
        //manaandskill
        drawTexturedModalRect(left+ ConfigHandler.leftmodify_mana, top+ConfigHandler.topmodify_mana,
                0, 40
                , 128, 32);
        //manaorb
        drawTexturedModalRect(left+ ConfigHandler.leftmodify_mana_orb, top+ConfigHandler.topmodify_mana_orb+loseManaLenghth,
                128, currentManaLength
                , 56, heightOrbMana);

        //drawlevelbar
        drawTexturedModalRect(left+ ConfigHandler.leftmodify_levelmain, top+ConfigHandler.topmodify_levelmain,
                0, 75
                , 90, 14);
        //drawlevelins
        //callength
        float rate= (float) PlayerDataHandler.get(mc.player).getCurrentExp()/PlayerDataHandler.get(mc.player).getMaxExp();
        int explength=MathHelper.ceil(rate*69);
        drawTexturedModalRect(left+ ConfigHandler.leftmodify_levelins, top+ConfigHandler.topmodify_levelins,
                0, 91
                , explength, 3);

        //drawlevelframe
        drawTexturedModalRect(left+ ConfigHandler.leftmodify_levelframe, top+ConfigHandler.topmodify_levelframe,
                0, 95
                , 90, 3);
        //drawleveltext
        FontRenderer fontRenderer = Minecraft.getMinecraft().fontRenderer;
        fontRenderer.drawStringWithShadow(PlayerDataHandler.get(mc.player).getLevel()+"",left+ConfigHandler.leftmodify_leveltext,
                top+ConfigHandler.topmodify_leveltext,ConfigHandler.leveltextcolor);
        //drawhealthtext
        fontRenderer.drawStringWithShadow("生命值:"+health+"/"+healthMax,left+ ConfigHandler.leftmodify_healthtext,
                top+ConfigHandler.topmodify_healttext,ConfigHandler.healthtextcolor);
        //drawmanatext
        fontRenderer.drawStringWithShadow("魔法值:"+mana+"/"+manaMax,left+ ConfigHandler.leftmodify_manatext,
                top+ConfigHandler.topmodify_manatext,ConfigHandler.manatextcolor);


        GlStateManager.disableBlend();
        //draw shortCutSkillRender
        try{
            PlayerDataShortCutTag playerDataShortCutTag = PlayerDataHandler.get(mc.player).getPlayerDataShortCutTag();

            //渲染CD
            playerDataShortCutTag.getShorCutSkillIcon(0).withBorder(Color4I.GRAY.withAlpha(30),false).draw(left+ConfigHandler.skill_1_x,top+ConfigHandler.skill_1_y,ConfigHandler.skill_1_size,ConfigHandler.skill_1_size);
            renderSkillCoverLayer(playerDataShortCutTag.getShorCutSkillName(0),mc.player,left+ConfigHandler.skill_1_x,top+ConfigHandler.skill_1_y,ConfigHandler.skill_1_size,ConfigHandler.skill_1_size);

            playerDataShortCutTag.getShorCutSkillIcon(1).withBorder(Color4I.GRAY.withAlpha(30),false).draw(left+ConfigHandler.skill_2_x,top+ConfigHandler.skill_2_y,ConfigHandler.skill_2_size,ConfigHandler.skill_2_size);
            renderSkillCoverLayer(playerDataShortCutTag.getShorCutSkillName(1),mc.player,left+ConfigHandler.skill_2_x,top+ConfigHandler.skill_2_y,ConfigHandler.skill_2_size,ConfigHandler.skill_2_size);

            playerDataShortCutTag.getShorCutSkillIcon(2).withBorder(Color4I.GRAY.withAlpha(30),false).draw(left+ConfigHandler.skill_3_x,top+ConfigHandler.skill_3_y,ConfigHandler.skill_3_size,ConfigHandler.skill_3_size);
            renderSkillCoverLayer(playerDataShortCutTag.getShorCutSkillName(2),mc.player,left+ConfigHandler.skill_3_x,top+ConfigHandler.skill_3_y,ConfigHandler.skill_3_size,ConfigHandler.skill_3_size);

            playerDataShortCutTag.getShorCutSkillIcon(3).withBorder(Color4I.GRAY.withAlpha(30),false).draw(left+ConfigHandler.skill_4_x,top+ConfigHandler.skill_4_y,ConfigHandler.skill_4_size,ConfigHandler.skill_4_size);
            renderSkillCoverLayer(playerDataShortCutTag.getShorCutSkillName(3),mc.player,left+ConfigHandler.skill_4_x,top+ConfigHandler.skill_4_y,ConfigHandler.skill_4_size,ConfigHandler.skill_4_size);

            playerDataShortCutTag.getShorCutSkillIcon(4).withBorder(Color4I.GRAY.withAlpha(30),false).draw(left+ConfigHandler.skill_5_x,top+ConfigHandler.skill_5_y,ConfigHandler.skill_5_size,ConfigHandler.skill_5_size);
            renderSkillCoverLayer(playerDataShortCutTag.getShorCutSkillName(4),mc.player,left+ConfigHandler.skill_5_x,top+ConfigHandler.skill_5_y,ConfigHandler.skill_5_size,ConfigHandler.skill_5_size);

            playerDataShortCutTag.getShorCutSkillIcon(5).withBorder(Color4I.GRAY.withAlpha(30),false).draw(left+ConfigHandler.skill_6_x,top+ConfigHandler.skill_6_y,ConfigHandler.skill_6_size,ConfigHandler.skill_6_size);
            renderSkillCoverLayer(playerDataShortCutTag.getShorCutSkillName(5),mc.player,left+ConfigHandler.skill_6_x,top+ConfigHandler.skill_6_y,ConfigHandler.skill_6_size,ConfigHandler.skill_6_size);

            playerDataShortCutTag.getShorCutSkillIcon(6).withBorder(Color4I.GRAY.withAlpha(30),false).draw(left+ConfigHandler.skill_7_x,top+ConfigHandler.skill_7_y,ConfigHandler.skill_7_size,ConfigHandler.skill_7_size);
            renderSkillCoverLayer(playerDataShortCutTag.getShorCutSkillName(6),mc.player,left+ConfigHandler.skill_7_x,top+ConfigHandler.skill_7_y,ConfigHandler.skill_7_size,ConfigHandler.skill_7_size);

            playerDataShortCutTag.getShorCutSkillIcon(7).withBorder(Color4I.GRAY.withAlpha(30),false).draw(left+ConfigHandler.skill_8_x,top+ConfigHandler.skill_8_y,ConfigHandler.skill_8_size,ConfigHandler.skill_8_size);
            renderSkillCoverLayer(playerDataShortCutTag.getShorCutSkillName(7),mc.player,left+ConfigHandler.skill_8_x,top+ConfigHandler.skill_8_y,ConfigHandler.skill_8_size,ConfigHandler.skill_8_size);
        }catch (Exception e){
            e.printStackTrace();
        }
        mc.renderEngine.bindTexture(Gui.ICONS);
    }

    /**渲染技能cd覆盖层
     *
     * @param skillName
     * @param playerSP
     * @param x
     * @param y
     * @param w
     * @param h
     */
    private void renderSkillCoverLayer(String skillName, EntityPlayerSP playerSP, int x, int y, int w, int h){

        if (null!= skillName){
            PlayerData playerData = PlayerDataHandler.get(playerSP);
           double cdRemaining= playerData.getSkillCdLeft(skillName);
            if (cdRemaining>0){
                // 绘制半透明的遮罩
                // 启用混合模式以支持透明度
                GlStateManager.enableBlend();
                GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);  // 设置默认的混合函数
                GlStateManager.enableAlpha();  // 启用 Alpha 测试

                Color4I maskColor = Color4I.rgb(64,64,64).withAlpha(150); // 设置遮罩颜色和透明度
                maskColor.draw(x, y, w, h); // 覆盖在技能图标上

                // 绘制 CD 剩余时间（数字）在遮罩上
                FontRenderer fontRenderer = Minecraft.getMinecraft().fontRenderer;
                String cdText = String.format("%.0f", cdRemaining); // 将剩余 CD 转换为字符串

                // 计算文本绘制的位置（居中）
                int textWidth = fontRenderer.getStringWidth(cdText);
                int textX = x + (w - textWidth) / 2;
                int textY = y + (h - fontRenderer.FONT_HEIGHT) / 2;

                // 设置文本颜色并绘制
                fontRenderer.drawString(cdText, textX, textY, 0xFFFFFFFF); // 0xFFFFFFFF 为白色

                GlStateManager.popMatrix();  // 恢复之前保存的 OpenGL 状态

                // 禁用混合模式以防止影响其他渲染操作
                GlStateManager.disableAlpha();
                GlStateManager.disableBlend();
            }
        }
    }

}
